import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:jiang_yue/home/PostShow.dart';
// import 'package:jiang_yue/modal/Article.dart';
// import 'package:jiang_yue/modal/Comment.dart';
// import 'package:jiang_yue/modal/User.dart';
import 'package:jiang_yue/utils/HttpUtils.dart';
import 'package:jiang_yue/utils/cache/UserCache.dart';
import 'package:jiang_yue/utils/cache/cache.dart';

class PostListView extends StatefulWidget {
  PostListView({Key key, this.type, this.title}) : super(key: key);

  final String type; // 需要查看的类型
  final String title;
  @override
  _PostListViewState createState() => _PostListViewState();
}

class _PostListViewState extends State<PostListView> {
  List posts=[];

  Widget judgeTimeOut(String lastTime, BuildContext context, var articleInfos) {
    int today = DateUtil.getNowDateMs();
    int activityLastTime = int.parse(lastTime);

    if (today > activityLastTime) {
      return Stack(
        children: <Widget>[
          Align(
            alignment: Alignment.centerLeft,
            child: Container(
              height: 30,
              width: 50,
              decoration: new BoxDecoration(
                border: new Border.all(color: Colors.grey, width: 0.5),
                borderRadius: new BorderRadius.circular((5.0)),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    ('已结束'),
                    style: TextStyle(color: Colors.grey),
                  ),
                ],
              ),
            ),
          ),
          Align(
            child: Text(
              articleInfos['title'],
              style: Theme.of(context).textTheme.title,
            ),
          ),
        ],
      );
    }

    return Stack(
        children: <Widget>[
          Align(
            alignment: Alignment.centerLeft,
            child: Container(
              height: 30,
              width: 50,
              decoration: new BoxDecoration(
                border: new Border.all(color: Colors.yellow[700], width: 0.5),
                borderRadius: new BorderRadius.circular((5.0)),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    ('进行中'),
                    style: TextStyle(color: Colors.yellow[700]),
                  ),
                ],
              ),
            ),
          ),
          Align(
            child: Text(
              articleInfos['title'],
              style: Theme.of(context).textTheme.title,
            ),
          ),
        ],
      );
  }

  Future _handlePostChangeLike(int userID, int articleID, bool isLike) async {
    Response response = await Dio().post("http://47.93.201.127:8080/jiangyue/like", data: {
      "userID": userID,
      "articleID": articleID,
      "like": isLike,
    });
  }

  Widget buildPosts(List posts, UserInfo userInfo) {
    return ListView.builder(
      itemCount: posts.length,
      itemBuilder: (BuildContext context, int index) {
        return Stack(
          children: <Widget>[
            Container(
                color: Colors.white,
                padding: EdgeInsets.fromLTRB(8, 0, 8, 0),
                child: Column(
                  children: <Widget>[
                    SizedBox(
                      height: 20,
                    ),
                    judgeTimeOut(posts[index]['lastTime'].toString(), context, posts[index]), //
                    SizedBox(height: 10),
                    Text(posts[index]['author'], style: TextStyle(fontSize: 14)),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      posts[index]['content'],
                      style: Theme.of(context).textTheme.subhead,
                      maxLines: 3,
                      overflow: TextOverflow.ellipsis,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Divider(
                      height: 1,
                    ),
                  ],
                )),
            Positioned.fill(
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                    splashColor: Colors.grey.withOpacity(0.3), // 慢慢展开的颜色
                    highlightColor: Colors.grey.withOpacity(0.1), // 高亮颜色
                    onTap: () {
                      int idx = getIndex(posts[index]['articleID']);
                      Navigator.push(
                        context,
                        new MaterialPageRoute(
                            builder: (context) => new PostShow(
                                  callback: _handlePostChangeLike,
                                  articleID: posts[index]['articleID'],
                                  index: idx,
                                )),
                      );
                    }),
              ),
            )
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    switch (widget.type) {
      case 'browse':
        browsePosts();

        break;
      case 'publish':
        publishPosts();
        break;
      case 'activity':
        joinPosts();
        break;
      case 'comment':
        commentPosts();
        break;
      default:
    }

    if (posts.length == 0) {
      return Scaffold(
        backgroundColor: Colors.grey[200],
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
          child: Text(
            '暂无数据',
            style: TextStyle(fontSize: 30, letterSpacing: 20, color: Colors.grey),
          ),
        ),
      );
    }

    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: buildPosts(posts, userInfo[0]),
    );
  }

  commentPosts() async {
    var result =
        await HttpUtils.request('http://47.93.201.127:8080/jiangyue/commentPosts', method: HttpUtils.GET, data: {
      "userID": userInfo[0].id,
    });
    if (result['success'] == true) {
      mycommentList = result['data']; //将数据放入cache.dart缓存
      if (posts.length != result['data'].length) {
        setState(() {
          posts = result['data'];
        });
      }
    }
  }

  browsePosts() async {
    var result =
        await HttpUtils.request('http://47.93.201.127:8080/jiangyue/browsePosts', method: HttpUtils.GET, data: {
      "userID": userInfo[0].id,
    });
    if (result['success'] == true) {
      browseList = result['data']; //将数据放入cache.dart缓存
      if (posts.length != result['data'].length) {
        setState(() {
          posts = result['data'];
        });
      }
    }
  }

  publishPosts() async {
    var result =
        await HttpUtils.request('http://47.93.201.127:8080/jiangyue/publishPosts', method: HttpUtils.GET, data: {
      "userID": userInfo[0].id,
    });

    if (result['success'] == true) {
      publishList = result['data']; //将数据放入cache.dart缓存
      if (posts.length != result['data'].length) {
        setState(() {
          posts = result['data'];
        });
      }
    }
  }

  joinPosts() async {
    var result = await HttpUtils.request('http://47.93.201.127:8080/jiangyue/joinPosts', method: HttpUtils.GET, data: {
      "userID": userInfo[0].id,
    });
    if (result['success'] == true) {
      joinList = result['data']; //将数据放入cache.dart缓存

      if (posts.length != result['data'].length) {
        setState(() {
          posts = result['data'];
        });
      }
    }
  }
}
